package initialize

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"go.uber.org/zap"
	"io"
	"net/http"
	"net/url"
	"nvr-http-proxy/internal/constant"
	"nvr-http-proxy/internal/domain"
	"nvr-http-proxy/internal/initialize/config"
	"strings"
)

type Login struct {
	svc config.ReadNvrConfig
}

func NewLogin(svc config.ReadNvrConfig) *Login {
	return &Login{svc: svc}
}

// InitLoginNvr
// 初始化登录nvr
func (p *Login) InitLoginNvr() (map[string]domain.LoginResponse, error) {
	respmap := make(map[string]domain.LoginResponse)
	nvrIpAddressMap, err := p.svc.InitReadNvrConfig()
	if err != nil {
		zap.S().Infof("读取NVR配置文件报错:%v", err)
		return nil, err
	}
	for _, v := range nvrIpAddressMap {
		loginUrl := fmt.Sprintf("%s%s", v.Addr, constant.NvrLiveQingLoginUrl)
		// 加密密码
		encryptedPassword := encryptPassword(v.Password)
		params := url.Values{}
		params.Add("username", v.Username)
		params.Add("password", encryptedPassword)
		params.Add("url_token_only", "true")    // 可选参数
		params.Add("token_timeout", "60480000") // 可选参数，这里是默认值
		// 构建完整的 URL
		requestURL := loginUrl + "?" + params.Encode()
		zap.S().Infof("NVR登录地址为:%s", requestURL)
		// 创建HTTP客户端
		client := &http.Client{}

		// 创建新的HTTP请求
		req, err := http.NewRequest("GET", requestURL, nil)
		if err != nil {
			zap.S().Errorw("创建新的HTTP请求失败", "msg", err.Error())
			return nil, err
		}
		// 设置请求头
		req.Header.Set("Accept", "*/*")
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
		req.Header.Set("Sec-Ch-Ua", `"Not)A;Brand";v="99", "Google Chrome";v="127", "Chromium";v="127"`)
		req.Header.Set("Sec-Ch-Ua-Mobile", "?0")
		req.Header.Set("Sec-Ch-Ua-Platform", `"Windows"`)
		req.Header.Set("User-Agent", `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36`)
		req.Header.Set("X-Requested-With", "XMLHttpRequest")

		// 发送HTTP请求
		resp, err := client.Do(req)
		if err != nil {
			zap.S().Errorw("Error making request:", err)
			return nil, err
		}
		defer resp.Body.Close()

		// 读取响应体
		body, err := io.ReadAll(resp.Body)
		if err != nil {
			zap.S().Errorw("Error reading response body:", err)
			return nil, err
		}
		// 打印响应状态码
		fmt.Println(v.Addr+"====>:Response Status Code:", resp.StatusCode)
		if resp.StatusCode == http.StatusOK {
			zap.S().Infof("Response Body:%s,%v", v.Addr, string(body))
			var liveQingResp domain.LoginResponse
			err := json.Unmarshal(body, &liveQingResp)
			if err != nil {
				zap.S().Errorf("Error unmarshalling response body:%s,%v", v.Addr, err)
				return nil, err
			}
			respmap[v.Addr] = liveQingResp
		}
	}
	return respmap, nil
}

// 加密密码函数
func encryptPassword(password string) string {
	hasher := md5.New()
	hasher.Write([]byte(strings.ToLower(password))) // 不区分大小写
	return hex.EncodeToString(hasher.Sum(nil))
}
